'use strict';

const Controller = require('../core/base_controller');
const fs = require('fs')
const pump = require('pump')
class ShopController extends Controller {
    // 保存头像/封面
    async saveAvatar() {
        const { ctx } = this;
        // 1. 取出上传的文件
        const parts = ctx.multipart({ autoFields: false });
        let files = {};
        let stream;
        // 2. 遍历parts 把文件流赋值给stream
        while ((stream = await parts()) != null) {
            if (!stream.filename) {
                // 9. 当stream流完了 则停止循环
                break;
            }
            // 3.获取文件名称
            const fieldname = stream.fieldname;
            // 4.获取流地址 和 线上地址
            const dir = await this.service.tools.getUploadFile(stream.filename);
            // 5.取出流地址
            const target = dir.uploadDir;
            // 6.创建一个写入流
            const writeStream = fs.createWriteStream(target);
            // 7.搭建管道 将stream流向我们的本地目录
            await pump(stream, writeStream);
            // 8.返回一个带线上地址的对象
            files = Object.assign(files, {
                [fieldname]: dir.saveDir
            });
        }

        if (Object.keys(files).length > 0) {
            ctx.body = {
                code: 200,
                message: '图片上传成功',
                data: files
            }
        } else {
            ctx.body = {
                code: 500,
                message: '图片上传失败',
                data: {}
            }
        }
    }
}

module.exports = ShopController;